import aplConst from "../utils/apl-const";
import config from "../utils/apl-config";

/*函数节流*/
function throttle(fn, interval) {
  var enterTime = 0; //触发的时间
  var gapTime = interval || 300; //间隔时间，如果interval不传，则默认300ms
  return function () {
    var context = this;
    var backTime = new Date(); //第一次函数return即触发的时间
    if (backTime - enterTime > gapTime) {
      fn.call(context, arguments);
      enterTime = backTime; //赋值给第一次触发的时间，这样就保存了第二次触发的时间
    }
  };
}

/*函数防抖*/
function debounce(fn, interval) {
  var timer;
  var gapTime = interval || 1000; //间隔时间，如果interval不传，则默认1000ms
  return function () {
    clearTimeout(timer);
    var context = this;
    var args = arguments; //保存此处的arguments，因为setTimeout是全局的，arguments不是防抖函数需要的。
    timer = setTimeout(function () {
      fn.call(context, args);
    }, gapTime);
  };
}

/*微信调取电话*/
function CallPhone(
  phoneNumber,
  successCallback = null,
  failCallback = null,
  completeCallback = null
) {
  wx.makePhoneCall({
    phoneNumber: phoneNumber, //要拨打的电话号码
    success: successCallback, //接口调用成功的回调函数
    fail: failCallback, //接口调用失败的回调函数
    complete: completeCallback, //接口调用结束的回调函数（调用成功、失败都会执行）
  });
}

/*微信调取电话*/
function MoneyFenToYuan(moneyFen) {
  return (moneyFen / 100).toFixed(2);
}

/*判断所在校区是否选择*/
function isSselectUniversityZone() {
  let localUniversity = wx.getStorageSync(aplConst.localUniversity);
  if (
    !localUniversity ||
    !localUniversity.hasOwnProperty("universityCode") ||
    localUniversity.universityCode == null ||
    localUniversity.universityCode == ""
  ) {
    return false;
  }
  return true;
}

/**上传图片回显 */
function uploadImageEcho(imageUrl) {
  let imageList = [];
  if (imageUrl) {
    let imageUrlArray = imageUrl.split(",");
    for (var i = 0; i < imageUrlArray.length; i++) {
      let url = "";
      url = config.fileDNS_upload + imageUrlArray[i];
      imageList = imageList.concat(url);
    }
  }
  return imageList;
}

/**设置监听器**/
function setWatcher(page) {
  let data = page.data;
  let watch = page.watch;
  Object.keys(watch).forEach((v) => {
    let key = v.split("."); // 将watch中的属性以'.'切分成数组
    let nowData = data; // 将data赋值给nowData
    for (let i = 0; i < key.length - 1; i++) {
      // 遍历key数组的元素，除了最后一个！
      nowData = nowData[key[i]]; // 将nowData指向它的key属性对象
    }
    let lastKey = key[key.length - 1];
    // 假设key==='my.name',此时nowData===data['my']===data.my,lastKey==='name'
    let watchFun = watch[v].handler || watch[v]; // 兼容带handler和不带handler的两种写法
    let deep = watch[v].deep; // 若未设置deep,则为undefine
    observe(nowData, lastKey, watchFun, deep, page); // 监听nowData对象的lastKey
  });
}
/**监听属性 并执行监听函数**/
function observe(obj, key, watchFun, deep, page) {
  var val = obj[key];
  // 判断deep是true 且 val不能为空 且 typeof val==='object'（数组内数值变化也需要深度监听）
  if (deep && val != null && typeof val === "object") {
    Object.keys(val).forEach((childKey) => {
      // 遍历val对象下的每一个key
      observe(val, childKey, watchFun, deep, page); // 递归调用监听函数
    });
  }
  let that = this;
  Object.defineProperty(obj, key, {
    configurable: true,
    enumerable: true,
    set: function (value) {
      watchFun.call(page, value, val); // value是新值，val是旧值
      val = value;
      if (deep) {
        // 若是深度监听,重新监听该对象，以便监听其属性。
        observe(obj, key, watchFun, deep, page);
      }
    },
    get: function () {
      return val;
    },
  });
}

/**设置注册参数 */
function setRegisterParam() {
  let registerParam = {
    /**密码 */
    psw: "",
    /**电话 */
    tel: "",
    /**来源渠道 */
    source: "",
    /**推荐码 */
    publicityFrom: "",
    /**使用区域 */
    useArea: "",
    /**用户信息对象 */
    userInfo: {},
    /**原始数据字符串 */
    rawData: {},
    /**sha1字符串 */
    signature: {},
    /**完整用户信息的加密数据 */
    encryptedData: {},
    /**加密算法的初始向量 */
    iv: {},
    /**登陆凭证 */
    code: "",
  };
  return registerParam;
}

/**
 * 生成随机密码
 * @param {*} length 密码长度
 */
function randomPassword(length) {
  length = Number(length)
  // Limit length
  if (length < 6) {
    length = 6
  } else if (length > 18) {
    length = 18
  }
  let passwordArray = ['ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz', '1234567890', '_'];
  var password = [];
  let n = 0;
  for (let i = 0; i < length; i++) {
    // If password length less than 9, all value random
    if ( password.length < (length - 4) ) {
      // Get random passwordArray index
      let arrayRandom = Math.floor(Math.random() * 4);
      // Get password array value
      let passwordItem = passwordArray[arrayRandom];
      // Get password array value random index
      // Get random real value
      let item = passwordItem[Math.floor(Math.random() * passwordItem.length)];
      password.push(item);
    } else {
      // If password large then 9, lastest 4 password will push in according to the random password index
      // Get the array values sequentially
      let newItem = passwordArray[n];
      let lastItem = newItem[Math.floor(Math.random() * newItem.length)];
      // Get array splice index
      let spliceIndex = Math.floor(Math.random() * password.length);
      password.splice(spliceIndex, 0, lastItem);
      n++
    }
  }
  return password.join("");
}

/**
 * 数据脱敏
 * @param {*} str 目标数据
 * @param {*} beginLen 前面显示位数
 * @param {*} endLen 后面显示位数
 */
function desensitization(str,beginLen,endLen) {
  var len = str.length;
  var firstStr = str.substr(0,beginLen);
  var lastStr = str.substr(endLen);
  var middleStr = str.substring(beginLen, len-Math.abs(endLen)).replace(/[\s\S]/ig, '*');
  var tempStr = firstStr + middleStr + lastStr;
  return tempStr;
}

/**
 * 在指定位置插入字符串
 * @param {*} soure 原字符串
 * @param {*} start 位置
 * @param {*} newStr 要插入的字符串
 * @description 使用场景1：moment不识别14位字符串，所以需要将年月日和时分秒进行分隔
 */
function insertStr(soure, start, newStr) {
  return soure.slice(0, start) + newStr + soure.slice(start);
}

export default {
  throttle,
  debounce,
  CallPhone,
  MoneyFenToYuan,
  isSselectUniversityZone,
  uploadImageEcho,
  setWatcher,
  setRegisterParam,
  randomPassword,
  desensitization,
  insertStr
};
